/*
 * @Author: 黄威
 * @Date: 2024-10-12 16:44:28
 * @LastEditors: leador-wcy 895308607@qq.com
 * @LastEditTime: 2024-11-01 13:49:20
 * @Description: 拆解 Drawer 和 Modal 的用法，方便 内容与容器拆分，以及后续统一样式修改
 */

import { useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { Button, Drawer, DrawerProps, Modal, ModalProps } from 'antd';
import { CloseOutlined } from '@ant-design/icons';

export default function useDrawer<T>(Comp: React.FunctionComponent<T>, drawerProps?: DrawerProps) {
  const [open, setIsOpen] = useState(false);
  const [props, setProps] = useState<any>();

  const openDrawer = useMemoizedFn((_props: Omit<T, 'onClose'>) => {
    setProps(_props);
    setIsOpen(true);
  });

  const closeDrawer = useMemoizedFn(() => {
    setIsOpen(false);
  });

  return {
    open,
    openDrawer,
    closeDrawer,
    Content: (
      <Drawer {...drawerProps} open={open} onClose={closeDrawer} closable={false} destroyOnClose getContainer={false}>
        <Button
          icon={<CloseOutlined />}
          onClick={closeDrawer}
          className="absolute top-2 right-2 bg-transparent border-none text-black text-lg cursor-pointer"
        />
        <Comp {...(props as any)} onClose={closeDrawer} />
      </Drawer>
    ),
  };
}

// 一个类似的 Modal
export function useModal<T>(Comp: React.FunctionComponent<T>, modalProps?: ModalProps) {
  const [open, setIsOpen] = useState(false);
  const [props, setProps] = useState<any>();

  const openModal = useMemoizedFn((_props: Omit<T, 'onClose'>) => {
    setProps(_props);
    setIsOpen(true);
  });

  const closeModal = useMemoizedFn(() => {
    setIsOpen(false);
  });

  return {
    open,
    openDrawer: openModal,
    closeDrawer: closeModal,
    Content: (
      <Modal {...modalProps} open={open} onClose={closeModal} destroyOnClose>
        <Comp {...(props as any)} onClose={closeModal} />
      </Modal>
    ),
  };
}
